<!DOCTYPE html>
<html>

<head>
    <title>Canvas动画</title>
</head>

<body>
    <canvas id="myCanvas" width="400" height="300" style="border:1px solid #000;"></canvas>
    <script>
        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');

        var squareSide = 140;
        var squareX = 200;
        var squareY = 150;
        var squareAngle = 0;

        var circleRadius = 30;
        var circleX = 30;
        var circleY = 70;
        var circleSpeed = 1;

        function draw() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            // 画方形
            ctx.save();
            ctx.translate(squareX, squareY);
            ctx.rotate(squareAngle * Math.PI / 180);
            ctx.fillStyle = 'blue';
            ctx.fillRect(-squareSide / 2, -squareSide / 2, squareSide, squareSide);
            ctx.restore();

            // 画圆
            ctx.fillStyle = 'red';
            ctx.beginPath();
            ctx.arc(circleX, circleY, circleRadius, 0, 2 * Math.PI);
            ctx.fill();

            // 更新位置和角度
            squareAngle += 1;
            circleX += circleSpeed;
            if (circleX > 300 | circleX < 30) {
                // circleX = 30;
                // circleY = 70;
                circleSpeed *= -1
            }

            requestAnimationFrame(draw);
        }

        draw();
    </script>
</body>

</html>